<template>
  <div>
    <a-spin :spinning="isLoading || isLoadingUpImg">
      <a-form :model="editForm" name="edit-form" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }" autocomplete="off"
        @finish="editPost" @validate="handleFormValidate">
        <div class="top_chg_language_div">
          <span style="text-align: center;" :class="{ 'active': tabsActiveKey === 'zh-cn' }"
            @click="changeLanguage('zh-cn')">中文</span>
          <span style="text-align: center;" :class="{ 'active': tabsActiveKey === 'en-us' }"
            @click="changeLanguage('en-us')">英文</span>
          <span style="text-align: center;" :class="{ 'active': tabsActiveKey === 'zh-hk' }"
            @click="changeLanguage('zh-hk')">繁体</span>
          <span style="text-align: center;" :class="{ 'active': tabsActiveKey === 'common' }"
            @click="changeLanguage('common')">通用配置</span>
        </div>
        <!-- 以下是中文 -->
        <div v-show="tabsActiveKey === 'zh-cn'">
          <a-form-item label="标题（中文）" name="title" :rules="[{ required: true, message: '请输入标题（中文）' }]">
            <a-input v-model:value="editForm.title" placeholder="请输入标题（中文）" />
          </a-form-item>
          <a-form-item label="副标题（中文）" name="desc" :rules="[{ required: true, message: '请输入副标题（中文）' }]">
            <a-input v-model:value="editForm.desc" placeholder="请输入副标题（中文）" />
          </a-form-item>
          <a-form-item label="援助标准（中文）" name="aid_standards" :rules="[{ required: true, message: '请输入援助标准（中文）' }]">
            <a-input v-model:value="editForm.aid_standards" placeholder="请输入援助标准（中文）" />
          </a-form-item>
          <a-form-item label="项目介绍（中文）" name="intro" :rules="[{ required: true, message: '请输入项目介绍（中文）' }]">
            <a-textarea v-model:value="editForm.intro" :rows="4" placeholder="请输入项目介绍（中文）" />
          </a-form-item>
          <a-form-item label="项目预算及执行计划（中文）" name="budget" :rules="[{ required: true, message: '请输入项目预算及执行计划（中文）' }]">
            <a-textarea v-model:value="editForm.budget" :rows="4" placeholder="请输入项目预算及执行计划（中文）" />
          </a-form-item>
          <a-form-item label="收款机构（中文）" name="organization_collection"
            :rules="[{ required: true, message: '请输入收款机构（中文）' }]">
            <a-input v-model:value="editForm.organization_collection" placeholder="请输入收款机构（中文）" />
          </a-form-item>
          <a-form-item label="执行机构（中文）" name="organization_execute"
            :rules="[{ required: true, message: '请输入执行机构（中文）' }]">
            <a-input v-model:value="editForm.organization_execute" placeholder="请输入>执行机构（中文）" />
          </a-form-item>
          <a-form-item :label="`负责人${n}（中文）`" v-for="n in organization_author_num">
            <a-space style="display: flex;" size="small">
              <a-form-item label="姓名" :name="['`organization_author[${n-1}]`', 'name']" style="margin-bottom: -24px;">
                <a-input v-model:value="editForm.organization_author[n - 1].name" placeholder="请输入姓名（中文）" />
              </a-form-item>
              <a-form-item label="职位" :name="['`organization_author[${n-1}]`', 'position']"
                style="margin-bottom: -24px;">
                <a-input v-model:value="editForm.organization_author[n - 1].position" placeholder="请输入职位（中文）" />
              </a-form-item>
              <a-form-item label="简介" :name="['`organization_author[${n-1}]`', 'desc']" style="margin-bottom: -24px;">
                <a-input v-model:value="editForm.organization_author[n - 1].desc" placeholder="请输入简介（中文）" />
              </a-form-item>
            </a-space>
          </a-form-item>
        </div>
        <!-- 以上是中文 -->
        <!-- 以下是英文 -->
        <div v-show="tabsActiveKey === 'en-us'">
          <a-form-item label="标题（英文）" name="title_us" :rules="[{ required: true, message: '请输入标题（英文）' }]">
            <a-input v-model:value="editForm.title_us" placeholder="请输入标题（英文）" />
          </a-form-item>
          <a-form-item label="副标题（英文）" name="desc_us" :rules="[{ required: true, message: '请输入副标题（英文）' }]">
            <a-input v-model:value="editForm.desc_us" placeholder="请输入副标题（英文）" />
          </a-form-item>
          <a-form-item label="援助标准（英文）" name="aid_standards_us" :rules="[{ required: true, message: '请输入援助标准（英文）' }]">
            <a-input v-model:value="editForm.aid_standards_us" placeholder="请输入援助标准（英文）" />
          </a-form-item>
          <a-form-item label="项目介绍（英文）" name="intro_us" :rules="[{ required: true, message: '请输入项目介绍（英文）' }]">
            <a-textarea v-model:value="editForm.intro_us" :rows="4" placeholder="请输入项目介绍（英文）" />
          </a-form-item>
          <a-form-item label="项目预算及执行计划（英文）" name="budget_us"
            :rules="[{ required: true, message: '请输入项目预算及执行计划（英文）' }]">
            <a-textarea v-model:value="editForm.budget_us" :rows="4" placeholder="请输入项目预算及执行计划（英文）" />
          </a-form-item>
          <a-form-item label="收款机构（英文）" name="organization_collection_us"
            :rules="[{ required: true, message: '请输入收款机构（英文）' }]">
            <a-input v-model:value="editForm.organization_collection_us" placeholder="请输入收款机构（英文）" />
          </a-form-item>
          <a-form-item label="执行机构（英文）" name="organization_execute_us"
            :rules="[{ required: true, message: '请输入执行机构（英文）' }]">
            <a-input v-model:value="editForm.organization_execute_us" placeholder="请输入>执行机构（英文）" />
          </a-form-item>
          <a-form-item :label="`负责人${n}（英文）`" v-for="n in organization_author_num">
            <a-space style="display: flex;" size="small">
              <a-form-item label="姓名" :name="['`organization_author[${n-1}]`', 'name_us']"
                style="margin-bottom: -24px;">
                <a-input v-model:value="editForm.organization_author[n - 1].name_us" placeholder="请输入姓名（英文）" />
              </a-form-item>
              <a-form-item label="职位" :name="['`organization_author[${n-1}]`', 'position_us']"
                style="margin-bottom: -24px;">
                <a-input v-model:value="editForm.organization_author[n - 1].position_us" placeholder="请输入职位（英文）" />
              </a-form-item>
              <a-form-item label="简介" :name="['`organization_author[${n-1}]`', 'desc_us']"
                style="margin-bottom: -24px;">
                <a-input v-model:value="editForm.organization_author[n - 1].desc_us" placeholder="请输入简介（英文）" />
              </a-form-item>
            </a-space>
          </a-form-item>
        </div>
        <!-- 以上是英文 -->
        <!-- 以下是繁体 -->
        <div v-show="tabsActiveKey === 'zh-hk'">
          <a-form-item label="标题（繁体）" name="title_hk" :rules="[{ required: true, message: '请输入标题（繁体）' }]">
            <a-input v-model:value="editForm.title_hk" placeholder="请输入标题（繁体）" />
          </a-form-item>
          <a-form-item label="副标题（繁体）" name="desc_hk" :rules="[{ required: true, message: '请输入副标题（繁体）' }]">
            <a-input v-model:value="editForm.desc_hk" placeholder="请输入副标题（繁体）" />
          </a-form-item>
          <a-form-item label="援助标准（繁体）" name="aid_standards_hk" :rules="[{ required: true, message: '请输入援助标准（繁体）' }]">
            <a-input v-model:value="editForm.aid_standards_hk" placeholder="请输入援助标准（繁体）" />
          </a-form-item>
          <a-form-item label="项目介绍（繁体）" name="intro_hk" :rules="[{ required: true, message: '请输入项目介绍（繁体）' }]">
            <a-textarea v-model:value="editForm.intro_hk" :rows="4" placeholder="请输入项目介绍（繁体）" />
          </a-form-item>
          <a-form-item label="项目预算及执行计划（繁体）" name="budget_hk"
            :rules="[{ required: true, message: '请输入项目预算及执行计划（繁体）' }]">
            <a-textarea v-model:value="editForm.budget_hk" :rows="4" placeholder="请输入项目预算及执行计划（繁体）" />
          </a-form-item>
          <a-form-item label="收款机构（繁体）" name="organization_collection_hk"
            :rules="[{ required: true, message: '请输入收款机构（繁体）' }]">
            <a-input v-model:value="editForm.organization_collection_hk" placeholder="请输入收款机构（繁体）" />
          </a-form-item>
          <a-form-item label="执行机构（繁体）" name="organization_execute_hk"
            :rules="[{ required: true, message: '请输入执行机构（繁体）' }]">
            <a-input v-model:value="editForm.organization_execute_hk" placeholder="请输入>执行机构（繁体）" />
          </a-form-item>
          <a-form-item :label="`负责人${n}（繁体）`" v-for="n in organization_author_num">
            <a-space style="display: flex;" size="small">
              <a-form-item label="姓名" :name="['`organization_author[${n-1}]`', 'name_hk']"
                style="margin-bottom: -24px;">
                <a-input v-model:value="editForm.organization_author[n - 1].name_hk" placeholder="请输入姓名（繁体）" />
              </a-form-item>
              <a-form-item label="职位" :name="['`organization_author[${n-1}]`', 'position_hk']"
                style="margin-bottom: -24px;">
                <a-input v-model:value="editForm.organization_author[n - 1].position_hk" placeholder="请输入职位（繁体）" />
              </a-form-item>
              <a-form-item label="简介" :name="['`organization_author[${n-1}]`', 'desc_hk']"
                style="margin-bottom: -24px;">
                <a-input v-model:value="editForm.organization_author[n - 1].desc_hk" placeholder="请输入简介（繁体）" />
              </a-form-item>
            </a-space>
          </a-form-item>
        </div>
        <!-- 以上是繁体 -->
        <!-- 以下是通用配置 -->
        <div v-show="tabsActiveKey === 'common'">
          <a-form-item label="累计捐款次数" name="donation_times_v" :rules="[{ required: true, message: '请输入累计捐款次数' }]">
            <a-input-number v-model:value="editForm.donation_times_v" :min="0" :max="999999999999"
              placeholder="请输入累计捐款次数" style="width: 100%;" />
          </a-form-item>
          <a-form-item label="累计捐款金额" name="donation_amount_v" :rules="[{ required: true, message: '请输入累计捐款金额' }]">
            <a-input-number v-model:value="editForm.donation_amount_v" :min="0" :max="999999999999"
              placeholder="请输入累计捐款金额" style="width: 100%;" />
          </a-form-item>
          <a-form-item label="累计 * 人获得帮助" name="donation_person_v"
            :rules="[{ required: true, message: '请输入累计 * 人获得帮助' }]">
            <a-input-number v-model:value="editForm.donation_person_v" :min="0" :max="9999999"
              placeholder="请输入累计 * 人获得帮助" style="width: 100%;" />
          </a-form-item>
          <a-form-item label="备案编号" name="organization_num" :rules="[{ required: true, message: '请输入备案编号' }]">
            <a-input v-model:value="editForm.organization_num" placeholder="请输入备案编号" />
          </a-form-item>
          <a-form-item label="显示顺序" name="sort" help="请输入显示顺序。范围1~1000，越小显示越靠前"
            :rules="[{ required: true, message: '请输入显示顺序。范围1~1000，越小显示越靠前' }]">
            <a-input-number v-model:value="editForm.sort" :min="1" :max="1000" placeholder="请输入显示顺序。范围1~1000，越小显示越靠前"
              style="width: 100%;" />
          </a-form-item>
          <a-form-item label="主图" name="zhu_img">
            <a-upload v-model:value="editForm.img" name="img" list-type="picture-card" class="avatar-uploader"
              :show-upload-list="false" :action="`${uploadUrl}donation`" @change="uploadFileChange" :accept="'image/*'"
              :headers="uploadAddHeaders" :data="uploadExtraData.img">
              <img v-if="editForm.img" :src="imgDomainUrl + editForm.img" style="max-width: 100%;max-height: 100%;" />
              <div v-else>
                <loading-outlined v-if="isLoadingUpImg"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="轮播图（不含主图）" name="sub_img">
            <a-upload v-model:value="editForm.img" name="img" list-type="picture-card" class="avatar-uploader"
              :show-upload-list="false" :action="`${uploadUrl}donation`" @change="uploadFileChange" :accept="'image/*'"
              :headers="uploadAddHeaders" :data="uploadExtraData.sub_img">
              <div>
                <loading-outlined v-if="isLoadingUpImg"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="已上传的轮播图" help="已上传的轮播图（可双击图片删除）" v-show="editForm.sub_img && editForm.sub_img.length > 0">
            <span id="sub_img_list">
              <img :src="imgDomainUrl + item" @dblclick="subImgDblClickDelete(index)"
                v-for="(item, index) in editForm.sub_img" />
            </span>
          </a-form-item>
          <a-form-item :label="`负责人${n} 头像`" v-for="n in organization_author_num">
            <a-upload v-model:value="editForm.organization_author[n - 1].head_img" name="img" list-type="picture-card"
              class="avatar-uploader organization_author_img" :show-upload-list="false" :action="`${uploadUrl}donation`"
              @change="uploadFileChange" :accept="'image/*'" :headers="uploadAddHeaders"
              :data="{ upload_type: 'organization_author', index: n - 1 }" style="width:60px;height:60px;">
              <img v-if="editForm.organization_author[n - 1].head_img"
                :src="imgDomainUrl + editForm.organization_author[n - 1].head_img"
                style="max-width: 100%;max-height: 100%;" />
              <div v-else>
                <loading-outlined v-if="isLoadingUpImg"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
          </a-form-item>
        </div>
        <!-- 以上是通用配置 -->

        <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
          <a-button type="primary" html-type="submit">立即提交</a-button>
          <a-button @click="editCancel" style="margin-left:10px;">取消</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue';
import { message } from 'ant-design-vue';
import { editDonation, getDonationDetail } from "@/api/admin";   //引入api
import { useRouter, useRoute } from 'vue-router';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';

const { uploadUrl, uploadAddHeaders } = inject('uploadInfo');  // 依赖注入--上传文件有关的配置
const { imgDomainUrl } = inject('imgDomainUrl');  // 依赖注入--文件、图片前的域名
const router = useRouter();
const route = useRoute();
const uploadExtraData = ref({
  img: { upload_type: 'img' },
  sub_img: { upload_type: 'sub_img' },
  organization_author: { upload_type: 'organization_author' },
});

const formValidateErrMsg = ref(false);  //是否显示form表单验证错误信息
// 表单验证
const handleFormValidate = (name, status, errorMsgs) => {
  // 控制只显示一个，不然错误太多就会全部显示，就把整个屏幕铺满错误信息了
  if (status === false && formValidateErrMsg.value === false) {
      formValidateErrMsg.value = true;
      setTimeout(() => { formValidateErrMsg.value = false; }, 2000);
      message.error(errorMsgs[0]);
      return false;
  }
};

const tabsActiveKey = ref('zh-cn');
const isLoading = ref(false);    // 控制loading
const isLoadingUpImg = ref(false);    // 控制loading（上传图片）

const editForm = ref({
  sort: 1000,
  organization_author: [],
  sub_img: [],
});  // 编辑表单
const organization_author_num = ref(5);  // 负责人个数
for (let i = 0; i < organization_author_num.value; i++) {
  editForm.value.organization_author.push({ name: '', position: '', desc: '', name_us: '', position_us: '', desc_us: '', name_hk: '', position_hk: '', desc_hk: '', head_img: '' });
}

const id = ref(route.query.id);  // 参数id
//根据参数id获取数据
const getUrlId = () => {
  const { checkURLParamsId } = inject('checkURLParamsId');  // 依赖注入--验证参数id正确性
  if (checkURLParamsId(id)) {
    isLoading.value = true;
    getDonationDetail({ id: id.value }).then((res) => {
      isLoading.value = false;
      if (res === false) return;

      editForm.value.id = res.data.id;
      editForm.value.donation_times_v = res.data.donation_times_v;
      editForm.value.donation_amount_v = res.data.donation_amount_v;
      editForm.value.donation_person_v = res.data.donation_person_v;
      editForm.value.img = res.data.img;
      editForm.value.sub_img = res.data.sub_img_arr;
      editForm.value.title = res.data.title;
      editForm.value.title_us = res.data.title_us;
      editForm.value.title_hk = res.data.title_hk;
      editForm.value.desc = res.data.desc;
      editForm.value.desc_us = res.data.desc_us;
      editForm.value.desc_hk = res.data.desc_hk;
      editForm.value.aid_standards = res.data.aid_standards;
      editForm.value.aid_standards_us = res.data.aid_standards_us;
      editForm.value.aid_standards_hk = res.data.aid_standards_hk;
      editForm.value.intro = res.data.intro;
      editForm.value.intro_us = res.data.intro_us;
      editForm.value.intro_hk = res.data.intro_hk;
      editForm.value.budget = res.data.budget;
      editForm.value.budget_us = res.data.budget_us;
      editForm.value.budget_hk = res.data.budget_hk;
      editForm.value.organization_num = res.data.organization_num;
      editForm.value.organization_collection = res.data.organization_collection;
      editForm.value.organization_collection_us = res.data.organization_collection_us;
      editForm.value.organization_collection_hk = res.data.organization_collection_hk;
      editForm.value.organization_execute = res.data.organization_execute;
      editForm.value.organization_execute_us = res.data.organization_execute_us;
      editForm.value.organization_execute_hk = res.data.organization_execute_hk;
      editForm.value.organization_author = res.data.organization_author_arr;
      editForm.value.sort = res.data.sort;

      console.log(editForm.value, '---------');
      console.log(res.data, '---------');
      // organization_author_num.value = res.data.organization_author.length;
      // editForm.value.id = res.data.id;
      // editForm.value.donation_id = String(res.data.donation_id);
      // editForm.value.author = res.data.author;
      // editForm.value.title = res.data.title;
      // editForm.value.title_us = res.data.title_us;
      // editForm.value.title_hk = res.data.title_hk;
      // editForm.value.content = res.data.content;
      // editForm.value.content_us = res.data.content_us;
      // editForm.value.content_hk = res.data.content_hk;
      // editForm.value.add_date = res.data.add_date;
      // editForm.value.img = res.data.img;
    }).catch((rej) => {
      isLoading.value = false;
      message.error('获取数据失败：' + rej);
      editCancel();
    });
  } else {
  }
}

// 获取接口数据列表
const editPost = () => {
  // console.log(editForm.value, '------------------------------------------------------------------------');
  // return;
  isLoading.value = true;

  if (editForm.value.img === undefined || editForm.value.img === null || editForm.value.img === '') {
    message.error('请上传主图');
    isLoading.value = false;
    return;
  }

  editDonation(editForm.value).then((res) => {
    if (res === false) return;

    message.success('操作成功，即将跳转……');
    setTimeout(() => { editCancel() }, 1000);
  }).catch((rej) => {
    isLoading.value = false;
    message.error('失败：' + rej);
  });
};

// 跳转到列表页
const editCancel = () => {
  isLoading.value = false;
  router.replace('/admin/donation/index');
}

// 轮播图--双击删除图片
const subImgDblClickDelete = (idx) => {
  editForm.value.sub_img.splice(idx, 1);
}

// 上传图片
const uploadFileChange = info => {
  if (info.file.status === 'uploading') {
    isLoadingUpImg.value = true;
    return;
  }
  if (info.file.status === 'done') {
    isLoadingUpImg.value = false;
    if (info.file.response.code === 0) {
      // 主图
      if (info.file.response.data.extra_params.upload_type === 'img') {
        editForm.value.img = info.file.response.data.down_path;
      } else if (info.file.response.data.extra_params.upload_type === 'sub_img') {
        // 轮播图
        editForm.value.sub_img.push(info.file.response.data.down_path);
      } else if (info.file.response.data.extra_params.upload_type === 'organization_author') {
        // 负责人
        editForm.value.organization_author[info.file.response.data.extra_params.index].head_img = info.file.response.data.down_path;
      }
    } else {
      message.error(info.file.response.message);
    }
  }
  if (info.file.status === 'error') {
    isLoadingUpImg.value = false;
    message.error('上传文件出错，请重新上传！');
  }
};

// 切换语言
const changeLanguage = (lan) => {
  tabsActiveKey.value = lan;
}

// 页面加载完成后，获取数据列表
onMounted(() => {
  getUrlId();
})
</script>

<style scoped>
#sub_img_list {
  display: flex;
  flex-direction: row;
  margin-top: 10px;
}

#sub_img_list img {
  margin-right: 10px;
  margin-bottom: 10px;
  width: 100px;
  max-height: 100px;
}

.top_chg_language_div {
  display: flex;
  flex-direction: row;
  width: 100%;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 30px;
}

.top_chg_language_div span {
  text-align: right;
  font-size: 18px;
  padding: 0 30px 20px 30px;
  letter-spacing: 5px;
  cursor: pointer;
}

.top_chg_language_div span:first-child {
  margin-left: 16.67%;
}

.top_chg_language_div>.active {
  color: #1677ff;
  font-weight: bold;
  border-bottom: 1px solid #1677ff;
}

:deep(.ant-tabs-nav) {
  padding-left: 17%;
}

:deep(.organization_author_img .ant-upload) {
  width: 100% !important;
  height: 100% !important;
}
</style>